import dayjs from 'dayjs'
import type { ConfigType } from 'dayjs'

const format = (date: ConfigType, template: string, defaultValue = '') => {
  const res = dayjs(date)
  return res.isValid() ? res.format(template) : defaultValue
}

export const dateTpl = 'YYYY-MM-DD'
export const timeTpl = 'HH:mm:ss'
export const timeTpl2 = 'HH:mm'

export const yearTpl = 'YYYY'

export const monthdayTpl = 'MM.DD'

export const datetimeTpl = `${dateTpl} ${timeTpl}`
export const datetimeFormat = (date: ConfigType, defaultValue = '') => format(date, datetimeTpl, defaultValue)
export const datetimeFormat2 = (date: ConfigType, defaultValue = '') => format(date, `${dateTpl} ${timeTpl2}`, defaultValue)
export const dateFormat = (date: ConfigType, defaultValue = '') => format(date, dateTpl, defaultValue)
export const timeFormat = (date: ConfigType, defaultValue = '') => format(date, timeTpl, defaultValue)
export const yearFormat = (date: ConfigType, defaultValue = '') => format(date, yearTpl, defaultValue)
export const monthdayFormat = (date: ConfigType, defaultValue = '') => format(date, monthdayTpl, defaultValue)
